var map = new AMap.Map('mapcontainer', {
    resizeEnable: true,
});
var stompClient
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'xinpai/car/select',
        datatype: "json",
        colModel: [
            { label: '车辆IMEI', name: 'imei', index: 'imei', width: 80,key: true },
            { label: '内部编号', name: 'interNum', index: 'inter_num', width: 80 },
            { label: '车辆类型', name: 'type', index: 'type', width: 80,formatter:function (value) {
                for(let  key in vo.dict.type){
                    for (let j = 0; j < vo.dict.type[key].length; j++) {
                        var obj =vo.dict.type[key][j];
                        if(obj.code==parseInt(value)){
                            return obj.value;
                        }
                    }
                }
                return value;
            }},
            { label: '车牌号码', name: 'plateNum', index: 'plate_num', width: 80 },
            { label: '燃料种类', name: 'fuelType', index: 'fuel_type', width: 80 ,formatter:function (value) {
                for (let j = 0; j < vo.dict.fuelType.length; j++) {
                    var obj =vo.dict.fuelType[j];
                    if(obj.code==parseInt(value)){
                        return obj.value;
                    }
                }
            }},
            { label: '关联负责人', name: 'leadingId', index: 'leading_id', width: 80,formatter:function (value) {
                    for (let j = 0; j < vo.userList.leadingId.length; j++) {
                        var obj =vo.userList.leadingId[j];
                        if(obj.uid==parseInt(value)){
                            return obj.name;
                        }
                    }
                return value;
            }},
            { label: '车辆状态', name: 'state', index: 'state', width: 50,formatter:function (value) {
                if(value==0){
                    return "<span class=\"label label-info\">离线</span>"
                }else if(value==1){
                    return "<span class=\"label label-success\">在线</span>"
                }
                return "未知"
            }},
            { label: '实时状态', name: 'inState', index: '', width: 50,formatter:function () {
                return "<a href=\"#\" class=\"btn btn-white btn-xs\" data-toggle=\"modal\" data-target=\"#runmodal\"><i class=\"fa fa-dashboard\" aria-hidden=\"true\"></i> 仪表盘</a>";
            }},
            { label: '实施油量', name: '', index: '', width: 50,formatter:function (value) {
                return "<div class=\"progress\"><div class=\"progress-bar progress-bar-warning\" role=\"progressbar\" aria-valuenow=\"50\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width:80%\">80%</div></div>"
            }},
            { label: '车辆告警', name: '', index: '', width: 50,formatter:function (value) {
                return "<span class='label label-danger'>超速</span>"
            }},
            { label: '车辆定位', name: '', index: '', width: 50,formatter:function () {
                return "<a ></a><i class=\"fa fa-map-marker\" aria-hidden=\"true\"></i> 查看位置</a>"
            }},
            { label: '视频监控', name: 'videoId', index: 'video_id', width: 80,formatter:function (value) {
                return '<div class="input-group">' +
                 '<button type="button" class="btn btn-primary btn-sm"><span class="fa fa-camera" aria-hidden="true"></span> 监控</button>' +
                 '<button type="button"  class="btn btn-info btn-sm"><span class="fa fa-video-camera" aria-hidden="true"></span> 回放</button>'+
                 '</div>'
            }}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumWidth: 25,
        autowidth:true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "list",
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        loadComplete:function (res) {
            if(res.code==0){
                let data={"fuelWear":0,"fuelWears":0,"oilMass":0,"temp":0,"s":0,"fuelRate":0,"EngineTime":0,"pressure":0,"rpm":0,"mileage":0};
                res.list.forEach(function (obj) {
                    let extData={imei:obj.imei,data:data}
                    vo.models.push(extData);
                    if(!isBlank(obj.location)){
                        let lng=obj.location.split(",");
                        let lngLat=new AMap.LngLat(lng[0],lng[1]);
                        let marker = new AMap.Marker({
                            icon: "../../statics/img/carRed.png",
                            position: lngLat,
                            extData:extData,
                            label:{
                                offset: new AMap.Pixel(-20,-30),
                                content: obj.plateNum
                            }
                        });
                        marker.on("click", function () {
                            let data=this.getExtData()
                            $('#runmodal').modal({backdrop: 'static', keyboard: false});
                            //connect()
                            vo.modelShow=data;
                            if(stompClient!=null){
                                vo.odb=stompClient.subscribe('/user/topic/odb', function (res) {
                                    vo.update(JSON.parse(JSON.parse(res.body).body))
                                })
                            }
                        })
                        map.add(marker);
                    }
                })

            }
            map.setFitView();
        }
        ,
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
        ,
        serializeGridData:function (postData) {
            let obj=GetRequest();
            postData.project_id=obj.pid;
            postData.nexus='true';
            return postData;
        },
        beforeSelectRow:function (rowid, e) {
            let list=map.getAllOverlays('marker');
            list.forEach(function (obj) {
                if(obj.getExtData().imei==parseInt(rowid)){
                    map.panTo(obj.getPosition());
                }
            })
        }
    });
});

var  gaugeOptions={

    chart: {
        type: 'solidgauge'
    },
    credits: {
        enabled: false
    },
    title: null,

    pane: {
        center: ['50%', '85%'],
        size: '140%',
        startAngle: -90,
        endAngle: 90,
        background: {
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
            innerRadius: '60%',
            outerRadius: '100%',
            shape: 'arc'
        }
    },

    tooltip: {
        enabled: false
    },

    // the value axis
    yAxis: {
        stops: [
            [0.1, '#55BF3B'], // green
            [0.5, '#DDDF0D'], // yellow
            [0.9, '#DF5353'] // red
            ],
        lineWidth: 0,
        minorTickInterval: null,
        tickAmount: 2,
        title: {
            y: -70
        },
        labels: {
            y: 16
        }
    },

    plotOptions: {
        solidgauge: {
            dataLabels: {
                y: 5,
                borderWidth: 0,
                useHTML: true
            }
        }
    }
}
const vo = new Vue({
    el:"#text",
    data: {
        jsession: null,
        odb:null,
        isInitFinished: false,
        swfwidth: 0,//swf插件窗口宽度
        swfheight: 0,//swf 插件窗口高度
        chnCount: 4,//默认通道数
        serverIp: "",//请求的服务器ip
        serverPort: "",//请求的服务器端口
        isLoadLoginServer: false,
        fileList: [],
        timeoutId:0,
        model:{data:null},
        models:[],
        modelShow:null,
        projectList:[],
        areaList:[],
        userList:{driverId:[],leadingId:[]},
        dict:{type:[],underpanType:[],fuelType:[]},
        positions:[]
    },
    methods:{
        init(data){
            let chartSpeed = Highcharts.chart('container-speed', Highcharts.merge(gaugeOptions, {
                yAxis: {
                    min: 0,
                    max: 150,
                    title: {
                        text: '车速'
                    }
                },

                credits: {
                    enabled: false
                },

                series: [{
                    name: 'Speed',
                    data: [data.s],
                    dataLabels: {
                        format: '<div style="text-align:center"><span style="font-size:25px;color:' +
                        ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
                        '<span style="font-size:12px;color:silver">km/h</span></div>'
                    },
                    tooltip: {
                        valueSuffix: ' km/h'
                    }
                }]

            }));

// The RPM gauge
            let chartRpm = Highcharts.chart('container-rpm', Highcharts.merge(gaugeOptions, {
                yAxis: {
                    min: 0,
                    max: 5000,
                    title: {
                        text: '发动机转速'
                    }
                },

                series: [{
                    name: '转速',
                    data: [data.rpm],
                    dataLabels: {
                        format: '<div style="text-align:center"><span style="font-size:25px;color:' +
                        ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.1f}</span><br/>' +
                        '<span style="font-size:12px;color:silver">* r/pm</span></div>'
                    },
                    tooltip: {
                        valueSuffix: ' revolutions/min'
                    }
                }]

            }));

            let chartFuel = Highcharts.chart('container-fuel', Highcharts.merge(gaugeOptions, {
                yAxis: {
                    min: 0,
                    max: 30,
                    title: {
                        text: '实时油耗'
                    }
                },

                series: [{
                    name: '升/百公里',
                    data: [data.fuelWear],
                    dataLabels: {
                        format: '<div style="text-align:center"><span style="font-size:25px;color:' +
                        ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.1f}</span><br/>' +
                        '<span style="font-size:12px;color:silver">* 升/百公里</span></div>'
                    },
                    tooltip: {
                        valueSuffix: ' revolutions/min'
                    }
                }]

            }));

            let chartJiYou = Highcharts.chart('container-jiaolongspeed', Highcharts.merge(gaugeOptions, {
                yAxis: {
                    min: 0,
                    max: 800,
                    title: {
                        text: '机油压力'
                    }
                },

                series: [{
                    name: 'kpa',
                    data: [data.pressure],
                    dataLabels: {
                        format: '<div style="text-align:center"><span style="font-size:25px;color:' +
                        ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.1f}</span><br/>' +
                        '<span style="font-size:12px;color:silver">* r/pm</span></div>'
                    },
                    tooltip: {
                        valueSuffix: ' revolutions/min'
                    }
                }]
            }));
            this.model={chartSpeed,chartJiYou,chartFuel,chartRpm,data};
            connect();
        },
        update(data){
            if(data.imei==this.modelShow.imei){
                if(this.model!=null){
                    this.model.chartFuel.series[0].points[0].update(data.fuelWear);
                    this.model.chartSpeed.series[0].points[0].update(data.s);
                    this.model.chartJiYou.series[0].points[0].update(data.pressure);
                    this.model.chartRpm.series[0].points[0].update(data.rpm);
                }
            }

        },
        selectDictList:function (name,type) {
            $.ajax({
                type: "GET",
                url:  baseURL + 'sys/dict/select',
                contentType: "application/json",
                data: {name},
                success: function(r){
                    if(r.code === 0){
                        for (let key in vo.dict) {
                            if(key==type){
                                vo.dict[key]=r.list;
                            }
                        }
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        selectUsersList:function (name,type) {
            $.ajax({
                type: "GET",
                url:  baseURL + 'xinpai/users/select',
                contentType: "application/json",
                data: {name},
                success: function(r){
                    if(r.code === 0){
                        vo.userList[type]=r.list;
                    } else{
                        alert(r.msg);
                    }
                }
            });
        }
    },
    created:function() {
        this.selectDictList("车辆类型",'type')
        this.selectDictList("燃料种类",'fuelType')
        this.selectUsersList("车队队长",'leadingId')
        let data={"fuelWear":0,"fuelWears":0,"oilMass":0,"temp":0,"s":0,"fuelRate":0,"EngineTime":0,"pressure":0,"rpm":0,"mileage":0};
        this.model.data=data;
        this.init(data);
    }
})
var p=[];
//连接服务器
function connect() {
    const socket = new SockJS('/endpointSang');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        stompClient.subscribe(`/user/${GetRequest().firmId}/gps`, function (response) {
            let dev=JSON.parse(response.body).car;
            let data=JSON.parse(JSON.parse(response.body).data.dataContent);
            let list=map.getAllOverlays('marker');
            list.forEach(function (obj) {
                if(obj.getExtData().imei==dev.imei&&dev.state==1){
                    var row=$("#jqGrid").jqGrid('getRowData',dev.imei);
                    row.state=1;
                    $("#jqGrid").jqGrid('getRowData',dev.imei);
                    $("#jqGrid").jqGrid('setRowData',dev.imei,row);
                    if(dev.location!=null&&$.inArray(dev.imei,p)!=-1){
                        var position=dev.location.split(",");
                        if(parseInt(data.sp)>1) {//速度大于0 表示已经移动
                            console.log("动了");
                            obj.setAngle(parseFloat(data.ag));
                            obj.moveTo(new AMap.LngLat(position[0], position[1]), parseInt(data.sp) * 1.852);
                        }else {
                            console.log("没动");
                            obj.setPosition(new AMap.LngLat(position[0], position[1]));
                        }
                    }else if(dev.location!=null&&$.inArray(dev.imei,p)==-1){
                        p.push(dev.imei)
                        var position=dev.location.split(",");
                        obj.setAngle(parseFloat(data.ag));
                        obj.setPosition(new AMap.LngLat(position[0], position[1]));
                    }
                }
            })
        });
    });
}
//转换坐标格式 为度
function positione(array) {
/*    var lng=Number(array[0].substring(3,array[0].length))/60;
    var lat=Number(array[1].substring(2,array[0].length))/60;
    lng=Number(array[0].substring(0,2)+lng.toString());
    lat=Number(array[1].substring(0,1)+lat.toString());*/
    var gcjloc = transformFromWGSToGCJ(array[0],array[1]);
    //console.log(gcjloc)
    return [gcjloc.lng,gcjloc.lat];
    //return [lng,lat];
}
/**
 * 用户登录
 * @param username
 * @param password
 */
var login = function (username, password) {
    if (username != null && password != null) {

        $.ajax(
            {
                type: 'get',
                url: `http://120.25.214.26/StandardApiAction_login.action?account=${username}&password=${password}`,
                success: function (data) {
                    let {jsession, result} = data;
                    if (result == 0) {
                        vo.jsession = jsession;
                        //getLng();
                    } else {
                        alert(`登录失败错误代码:${result}`);
                    }
                },
                error: function () {
                    alert('登录失败');
                }
            }
        );
    }
}
/**
 * 用户注销
 * @param jsession
 */
var logout = function (jsession) {

    if (jsession) {
        $.ajax(
            {
                type: 'get',
                url: `http://120.25.214.26/StandardApiAction_logout.action?jsession=${jsession}`,
                success: function (data) {
                    console.log(data);
                }
            }
        );
    }
}





